import React, { Component } from 'react';
import { Modal, View, TouchableOpacity } from 'react-native';
import PropTypes, { oneOf, oneOfType } from 'prop-types';

import { noop } from 'bee/utils';
import styles from './style';

class Mask extends Component {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
    };

    this.close = this.close.bind(this);
    this.open = this.open.bind(this);
  }

  open() {
    this.setState({
      visible: true,
    });
  }

  close() {
    this.setState({
      visible: false,
    });
  }

  render() {
    const {
      children,
      onRequestClose,
      animationType,
      contentPosition,
    } = this.props;

    const hasTwoChild = children.length === 2;

    return (
      <View style={{ flex: 1 }}>
        {hasTwoChild && (
          <TouchableOpacity onPress={this.open}>{children[0]}</TouchableOpacity>
        )}
        <Modal
          transparent
          visible={this.state.visible}
          onRequestClose={onRequestClose}
          animationType={animationType}
        >
          <View style={[styles.mask, styles[contentPosition]]}>
            {hasTwoChild ? children[1] : children}
          </View>
        </Modal>
      </View>
    );
  }
}

Mask.propTypes = {
  animationType: oneOf(['none', 'slide', 'fade']),
  onRequestClose: PropTypes.func,
  children: oneOfType([
    PropTypes.arrayOf(PropTypes.element),
    PropTypes.element,
  ]),
  contentPosition: oneOf(['center', 'top', 'bottom']).isRequired,
};

Mask.defaultProps = {
  animationType: 'fade',
  onRequestClose: noop,
  children: null,
};
export default Mask;
